<?
/**************************************************************************************************
 Name: VPS Web Save Order
 System: VPS
 Sub-system: Vendor Components
 Description: Script to initiate a transaction with the VPS
 Version: 1.2 - 26-jan-05
 History:  
 Version Author   Date and Notes
     1.2 Peter G  26-jan-05 - Update protocol 2.20 -> 2.22
     1.1          10-sep-03 - PHP release
     1.0                      ASP release
*************************************************************************************************/

// *** Include the initialisation files
include ("init-includes.php");


// Set some variables
$TargetURL = $PurchaseURL;													// Specified in init-includes.php
$VerifyServer = $Verify;														// Specified in init-includes.php

/**************************************************************************************************
	Retrieve order information from your database
**************************************************************************************************/

	/*
	Example code for connecting to a MySQL database
	*/

	// Make the connection
	$db = mysql_connect($myHost, $myUser, $myPass);

	// Select the database
	mysql_select_db($myDB,$db);

	// 
	$sql = "SELECT * from $myTable
		WHERE VendorTxCode='" . $_POST["VendorTxCode"] . "'
	";

	// Get the query object
	@$result=mysql_query($sql,$db);
	
	// Get the row
	$row=mysql_fetch_array($result);


// Set order description
// If there's an alternate description, use it (truncated to 100 characters) otherwise use default
if ($_POST['Description'] != ''){
	$Description = substr($_POST['Description'],0,100);
} else {
	$Description = $DefaultDescription;								//  Specified in init-protx.php
}

/**************************************************************************************************
	Set all the required outgoing properties for the initial HTTPS post to the VPS
**************************************************************************************************/

// Create an array of values to send
$required = array (
		'VPSProtocol' => $ProtocolVersion, 							// Protocol version (specified in init-includes.php)
		'TxType' => $row['TxType'],											// Transaction type
		'Vendor' => $Vendor,														// Vendor name (specified in init-protx.php)
		'VendorTxCode' => $row['VendorTxCode'],					// Unique transaction code (generated by vendor)
		'Amount' => $row['Amount'],											// Value of order (supplied by vendor)
		'Currency' => $DefaultCurrency,									// Currency of order (default specified in init-protx.php)
		'Description' => $Description,									// Description of order 
	);

// add optional fields to the data array only if they've been set
$data = addOptionalFields( $_POST, $required, array ( 
  'ContactNumber',
  'ContactFax',
  'CustomerName',
  'CustomerEMail',
  'GiftAidPayment',
  'ApplyAVSCV2',
  'ClientIPAddress',
  'CAVV',
  'XID',
  'ECI',
  '3DSecureStatus',
  'Basket',
  'ClientNumber', 
  'IssueNumber', 
  'CV2', 
) );

// Add card holder name
$data['CardHolder'] = $_POST['CardHolder'];
// Add card number
$data['CardNumber'] = $_POST['CardNumber'];

// Check if start date is supplied
if($_POST['StartDateMonth']){
	// If so, add start date to data array to be appended to POST
	$data['StartDate'] = $_POST['StartDateMonth'] . $_POST['StartDateYear'];
}

// Add expiry date
$data['ExpiryDate'] = $_POST['ExpiryDateMonth'] . $_POST['ExpiryDateYear'];

// Add card type
$data['CardType'] = $_POST['CardType'];

// Check if address and/or postcode are supplied
if($row['BillingAddress']){
	// If so, add address (truncated to 200 characters) to data array to be appended to POST
	$data["BillingAddress"] = substr($row['BillingAddress'],0,200);
}
if($row['BillingPostCode']){
	// If so, add postcode (truncated to 10 characters) to data array to be appended to POST
	$data["BillingPostCode"] = substr($row['BillingPostCode'],0,10);
}

// Check if address and/or postcode are supplied
if($row['DeliveryAddress']){
	// If so, add address (truncated to 200 characters) to data array to be appended to POST
	$data["DeliveryAddress"] = substr($row['DeliveryAddress'],0,200);
}
if($row['DeliveryPostCode']){
	// If so, add postcode (truncated to 10 characters) to data array to be appended to POST
	$data["DeliveryPostCode"] = substr($row['DeliveryPostCode'],0,10);
}

// Format values as url-encoded key=value pairs
$data = formatData($data);

/**************************************************************************************************
	Send the post to the target URL
		if anything goes wrong with the connection process:
			- $response["Status"] will be 'FAIL';
			- $response["StatusDetail"] will be set to describe the problem;
**************************************************************************************************/
$response = requestPost($TargetURL, $data);

/*************************************************************************************************
  Update the database with returned details
**************************************************************************************************/

/*
	If the transaction is successful (Status is OK), 
  then you must store the VPSTxId and the SecurityKey, 
  returned from the VPS, against your own unique transaction id for this purchase, 
  in your database.
	These will be needed later to identify the transaction the VPS is notifying you about,
	and for any refunds you may wish to make against this purchase in the future.

	The VPSTxId and Security Key are returned in $response["VPSTxId"] and $response["SecurityKey"] respectively.

  In this example, we store all returned details in all circumstances.
*/

	// Demo code for updating a mySQL database

	// Set the query (update existing record)
	$sql = "UPDATE $myTable
		SET 
			Status = '" . $response["Status"] . "',
			StatusDetail = '" . mysql_escape_string( $response["StatusDetail"] ) . "',
			VPSTxId = '" . $response["VPSTxId"] . "',
			SecurityKey = '" . $response["SecurityKey"] . "',
			TxAuthNo = '" . $response["TxAuthNo"] . "',
			AVSCV2 = '" . $response["AVSCV2"] . "',
			AddressResult = '" . $response["AddressResult"] . "',
			PostCodeResult = '" . $response["PostCodeResult"] . "',
			CV2Result = '" . $response["CV2Result"] . "' WHERE id = " . $_POST["id"]
	;

	// Get the query as an associative array
	@$result=mysql_query($sql,$db);

/**************************************************************************************************
	Check the Status and act appropriately
'*************************************************************************************************/

// Get the first word of the status -- in case it has appended values (eg. REPEATED)
$baseStatus = array_shift(split(" ",$response["Status"]));

switch($baseStatus) {

	case 'OK':
		/**************************************************************************************************
			Transaction registered successfully, now redirect the user to your success URL.
		**************************************************************************************************/
		header("Location: " . $DefaultCompletionURL . "?VendorTxCode=" . $row['VendorTxCode']);

		break; // END case 'OK'

	/*
		In all following cases, the status is not OK. 
    You may wish to check the status field in your database at a later date, 
    to enable you to delete orders that did not complete.
	*/

	case 'NOTAUTHED':
		/**************************************************************************************************
			Transaction was not authorised.
			Redirect the user to your not authorised URL.
		**************************************************************************************************/
		header("Location: " . $DefaultNotAuthedURL);

		break; // END case 'NOTAUTHED'

	case 'REJECTED':
		/**************************************************************************************************
			Transaction was rejected.
			Redirect the user to your rejected URL.
		**************************************************************************************************/
		header("Location: " . $DefaultRejectedURL);

		break; // END case 'REJECTED'

	// Connection timed out
	case 'FAIL':
		/**************************************************************************************************
			Connection to protx could not be made (timed out)
		**************************************************************************************************/


		echo ("
			<HTML>
			<BODY>
			Connection to protx server failed.<BR><BR>
			Status=" . $response['Status'] . "<BR>
			StatusDetail=" . $response['StatusDetail'] . "<BR>
			</BODY>
			</HTML>
		");

		break; // END case 'FAIL'

	// There was an error of some kind
	default:
		/**************************************************************************************************
			Status was not OK, so whilst communication was successful, something was wrong with the POST
			Display information about the error on screen and update your database with this information
		**************************************************************************************************/

		echo ("
			<HTML>
			<BODY>
			Communication with the PROTX Server " . $TargetURL . " was successful but transaction was not registered.  See details below:<BR><BR>
			Status=" . $response['Status'] . "<BR>
			StatusDetail=" . $response['StatusDetail'] . "<BR>
			Protocol=" . $response['VPSProtocol'] . "<BR>
		" );

		if (isset($response['VPSTxId'])){
			echo("
				VPSTxId=" . $response['VPSTxId'] . "<BR>
				SecurityKey=" . $response['SecurityKey'] . "<BR>
				NextURL=" . $response['NextURL'] . "
			");
		}

		echo("
			</BODY>
			</HTML>
		");

		break; // END default

} // END switch($bastStatus)

// Close the database	connection
mysql_close($db);

?>
